<template>
	<view class="page flex flex-direction">
		<cu-custom :isBack="true" class="bg-blue" :backPress="clickBack">
			<block slot="backText">返回</block>
			<block slot="content">{{device.projectName}}</block>
		</cu-custom>
		<view class="container flex flex-sub flex-direction">
			<view class="container_body flex-sub" style="position: relative;">
				<!-- 第二层  -->
				<view class="container_target">
					<view class="cu-list grid col-2">
						<view class="cu-item no-border" :key="index" v-for="(item,index) in device.patrolFacilityCheckItemsVos"
						 :data-index="index" @tap="clickTargetItem">
							<view class="cu-item_card">
								<view class="cu-item_card_image">
									<image :src="baseUrl+'mcs'+item.imgUri" mode="widthFix" class="response"></image>
								</view>
								<view class="text-bold text-black" style="margin-top: 5px;">
									{{item.name}}
								</view>
								<view class="cu-item_card_badge bg-red text-white" v-if="item.dangerCount && item.dangerCount>0">
									{{item.dangerCount}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 第三层巡检点 -->
				<view class="container_point" v-if="currentTarget">
					<view class="container_point_card bg-white shadow" :key="index" v-for="(item,index) in currentTarget.patrolFacilityCheckItemContents"
					 @tap="clickPointItem" :data-index="index">
						<view class="cf padding-xs">
							<view class="fl">
								{{item.checkType}}
								<span v-if="item.checkType=='抄表项'">-{{item.meterReadingType}}</span>
							</view>
							<view class="fr" v-if="item.checkType=='检查项'">
								<view class="fr text-red" v-if="item.dangerCount && item.dangerCount>0">
									{{item.dangerCount}}条隐患
								</view>
								<view class="fr text-green" v-else>
									正常
								</view>
							</view>
							<view class="fr" v-if="item.checkType=='抄表项'">
								<view class="text-green" v-if="item.dangerCount && item.dangerCount>0">
									已记录
								</view>
								<view class="text-red" v-else>
									未记录
								</view>
							</view>

						</view>
						<view class="text-black text-bold padding-xs">
							{{item.checkContent}}
						</view>
					</view>
				</view>
			</view>
			<!-- 提交按钮 -->
			<view class="submit">
				<button class="cu-btn bg-blue" @tap="clickSubmit">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		uuid
	} from 'vue-uuid';
	import {
		mapGetters
	} from 'vuex'
	import constant from '../../util/constant.js'
	import ui from '../../util/ui.js'
	import patrolUtil from '../../util/patrolUtil.js'

	let that = null;
	export default {
		data() {
			return {
				baseUrl: constant.baseUrl,
				device: {},
				record: {},
				currentTarget: null,
				currentPoint: null
			}
		},
		computed: {
			...mapGetters(['userInfo'])
		},
		onLoad(options) {
			that = this;
			let device = JSON.parse(decodeURIComponent(options.device));
			that.device = device;
			// 初始化record
			that.record.facilityCheckId = that.device.id;
			that.record.facilityCheckTitle = that.device.projectName;
			that.record.patrolTime = new Date().getTime();
			that.record.patrolEmployeeId = that.userInfo.userId;
			that.record.patrolEmployeeName = that.userInfo.name;
			that.record.hasReport = 0;
			that.record.contents = [];
			for (let i = 0; i < that.device.patrolFacilityCheckItemsVos.length; i++) {
				let target = that.device.patrolFacilityCheckItemsVos[i];
				for (let j = 0; j < target.patrolFacilityCheckItemContents.length; j++) {
					let point = target.patrolFacilityCheckItemContents[j];
					let danger = {
						facilityCheckRecordId: that.device.id,
						itemId: target.id,
						itemName: target.name,
						checkType: point.checkType,
						checkContentId: point.id,
						itemTitle: point.checkName,
						checkContent: point.checkContent,
						hasError: 0,
						contentDesc: '',
						dangerId: uuid.v4(),
						meterReadingType: point.meterReadingType,
						meterContent: '',
						meterLowerLimit: point.meterLowerLimit,
						meterUpperLimit: point.meterUpperLimit,
						meterOptions: point.meterOptions,
						attachmentLocalList: []
					};
					that.record.contents.push(danger)
				}
			}

			// 注册监听事件
			uni.$on('updateDeviceDanger', danger => {
				// 找到record中的danger并删除  添加此danger
				that.record.contents.splice(that.findDangerIndexInRecord(danger.checkContentId), 1);
				that.record.contents.push(danger);
				// 更新target 和 points中的errorCount
				that.updateTargetErrorCount();
				that.updatePointErrorCount();
				// 强行刷新
				that.$forceUpdate();
			})
		},
		onBackPress(event) {
			if (event.from == 'backbutton') {
				that.clickBack();
				return true;
			} else {
				return false;
			}
		},
		onUnload() {
			// 注销监听事件
			uni.$off('updateDeviceDanger');
		},
		methods: {
			// —————————————————————————————点击方法—————————————————————————————————
			/**
			 * 点击返回时的事件
			 */
			clickBack: function() {
				// 首先判断是否是target页面
				if (that.currentTarget == null) {
					uni.showModal({
						title: "提示",
						content: "正在巡检中，是否终止巡检？",
						cancelText: "取消",
						cancelColor: "#737373",
						confirmText: "终止",
						confirmColor: "#E64340",
						success(res) {
							if (res.confirm) {
								uni.navigateBack()
							}
						}
					})
				} else {
					that.currentTarget = null;
				}
			},
			/**
			 * 点击target列表的事件
			 * @param {Object} e
			 */
			clickTargetItem: function(e) {
				let index = e.currentTarget.dataset.index;
				let targetList = that.device.patrolFacilityCheckItemsVos;
				that.currentTarget = targetList[index];
			},
			/**
			 * 点击points列表时的事件
			 * @param {Object} e
			 */
			clickPointItem: function(e) {
				let point = that.currentTarget.patrolFacilityCheckItemContents[e.currentTarget.dataset.index];
				// 从record中找到danger
				let danger = that.findDangerInRecord(point.id);
				if (danger == null) {
					return;
				}
				// 判断是巡检项还是抄表项
				let patrolType = danger.checkType;
				if (patrolType == '检查项') {
					uni.navigateTo({
						url: './patrol_device_danger_add?danger=' + encodeURIComponent(JSON.stringify(danger))
					})
				} else if (patrolType == '抄表项') {
					uni.navigateTo({
						url: './patrol_device_meter_add?danger=' + encodeURIComponent(JSON.stringify(danger))
					})
				}
			},
			/**
			 * 提交
			 */
			clickSubmit: function() {
				uni.showModal({
					title: '上传',
					content: '确定上传本次巡检数据？',
					cancelText: '取消',
					confirmText: '确定',
					success(res) {
						if (res.confirm) {
							console.log(that.record);
							// 检查抄表项是否完成
							let count = that.checkMeterFinish();
							if (count > 0) {
								// 说明没有完成
								ui.showErrorDialog('请将抄表项填写完整再提交')
								return
							}
							// 完成结束的数据
							that.record.errorCount = that.findRecordErrorCount();
							console.log(that.record);
							patrolUtil.uploadDeviceRecord(that.record, res => {
								uni.showModal({
									title: "成功",
									content: "巡查记录上传成功!",
									showCancel: false,
									confirmText: '确定',
									success(res) {
										if (res.confirm) {
											uni.navigateBack()
										}
									}
								})
							})
						}
					}
				})
			},

			// —————————————————————————————其他方法—————————————————————————————————
			/**
			 * 
			 */
			findDangerInRecord: function(pointId) {
				for (let i = 0; i < that.record.contents.length; i++) {
					let danger = that.record.contents[i];
					if (pointId == danger.checkContentId) {
						return danger;
					}
				}
				return null;
			},
			/**
			 * 根据point id在record中寻找index
			 * @param {Object} pointId
			 */
			findDangerIndexInRecord: function(pointId) {
				for (let i = 0; i < that.record.contents.length; i++) {
					let danger = that.record.contents[i];
					if (pointId == danger.checkContentId) {
						return i;
					}
				}
				return -1;
			},
			/**
			 * 刷新target
			 */
			updateTargetErrorCount: function() {
				for (let i = 0; i < that.device.patrolFacilityCheckItemsVos.length; i++) {
					let target = that.device.patrolFacilityCheckItemsVos[i];
					let count = 0;
					for (let j = 0; j < that.record.contents.length; j++) {
						let danger = that.record.contents[j];
						if (target.id == danger.itemId && danger.hasError == 1) {
							count++;
						}
					}
					target.dangerCount = count;
				}
			},
			/**
			 * 刷新points
			 */
			updatePointErrorCount: function() {
				for (let i = 0; i < that.device.patrolFacilityCheckItemsVos.length; i++) {
					let target = that.device.patrolFacilityCheckItemsVos[i];
					for (let j = 0; j < target.patrolFacilityCheckItemContents.length; j++) {
						let point = target.patrolFacilityCheckItemContents[j];
						let count = 0;
						for (let k = 0; k < that.record.contents.length; k++) {
							let danger = that.record.contents[k];
							if (danger.checkType == '检查项') {
								if (point.id == danger.checkContentId && danger.hasError == 1) {
									count++;
								}
							} else if (danger.checkType == '抄表项') {
								if (point.id == danger.checkContentId && danger.meterContent.length > 0) {
									count++;
								}
							}
						}
						point.dangerCount = count;
					}
				}
			},
			/**
			 * 计算record中danger的数量
			 */
			findRecordErrorCount: function() {
				let count = 0;
				for (let i = 0; i < that.record.contents.length; i++) {
					let danger = that.record.contents[i];
					if (danger.hasError == 1) {
						count++;
					}
				}
				return count;
			},
			/**
			 * 检查抄表项是否全部完成
			 */
			checkMeterFinish: function() {
				let num = 0;
				for (let i = 0; i < that.record.contents.length; i++) {
					let danger = that.record.contents[i];
					if (danger.checkType == '抄表项' && danger.meterContent.trim().length == 0) {
						num++;
					}
				}
				return num;
			}
		}
	}
</script>

<style>
	.container_target,
	.container_point {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
	}

	.container_target {}

	.cu-item_card {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	.cu-item_card_badge {
		position: absolute;
		right: 10px;
		top: 0px;
		width: 20px;
		height: 20px;
		line-height: 20px;
		text-align: center;
		border-radius: 50%;
	}

	.cu-item_card_image {
		width: 120px;
		height: 120px;
		background-size: cover;
		background-image: url('../../static/patrol/patrol_mobile_device_default_image.webp');
	}

	.container_point {
		background-color: #F1F1F1;
	}

	.container_point_card {
		margin: 10px;
		background-color: white;
		border-radius: 5px;
		padding: 10px;
		overflow: hidden;
	}

	.container .submit {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px;
	}

	.container .submit button {
		width: 80px;
		height: 80px;
		border-radius: 50%;
	}
</style>
